use reqwest::Client;
use semver::{Version, VersionReq};
use crate::VERSION;

pub async fn check_update() -> Result<Option<String>, UpdateError> {
    let client = Client::new();
    let response = client.get("https://api.yam.org/latest-version")
        .send()
        .await?
        .text()
        .await?;

    let latest_version = Version::parse(&response)?;
    let current_version = Version::parse(VERSION)?;

    if latest_version > current_version {
        Ok(Some(response))
    } else {
        Ok(None)
    }
}

pub async fn perform_update(new_version: &str) -> Result<(), UpdateError> {
    let url = format!("https://download.yam.org/yam-{}-x86_64-unknown-linux-gnu.tar.gz", new_version);
    
    // 下载并替换二进制文件
    let temp_dir = tempfile::tempdir()?;
    let download_path = temp_dir.path().join("yam.tar.gz");
    
    crate::download::download_file(&url, &download_path).await?;
    crate::archive::extract_tar_gz(&download_path, temp_dir.path())?;
    
    // 替换当前可执行文件
    #[cfg(unix)]
    std::fs::rename(temp_dir.path().join("yam"), std::env::current_exe()?)?;

    Ok(())
}